package com.clkj.tramcarlibrary.aroundtaxi;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.util.Log;
import android.view.Window;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.RotateAnimation;
import com.clkj.tramcarlibrary.R;
import com.clkj.tramcarlibrary.constant.Constants;
import com.clkj.tramcarlibrary.entity.AroundTaxiInfo;
import com.clkj.tramcarlibrary.http.HttpService;
import com.clkj.tramcarlibrary.schedulers.SchedulerProvider;
import com.clkj.tramcarlibrary.tram.TramcarActivity;
import com.clkj.tramcarlibrary.util.CommonUtil;
import com.clkj.tramcarlibrary.util.SensorEventHelper;
import com.clkj.tramcarlibrary.util.ToastUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.functions.Action1;

/**
 * 周边的出租车ac
 * Created by Administrator on 2017/1/23.
 */

public class ActivityTaxiAroundView extends AppCompatActivity implements LocationSource,
        AMapLocationListener, AroundTaxiContract.View {

    private ImageView ivBack;
    private TextView tvTramcar;
    //private FloatingActionButton fbTakeTaxi;
    private TextView tvTakeTaxi;


    private AMap aMap;
    private MapView mMapView;
    private OnLocationChangedListener mOnLocationChangeListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    private boolean mFirstFix = false;
    private Marker mLocMarker;
    private SensorEventHelper mSensorHelper;
    private Circle mCircle;
    public static final String LOCATION_MARKER_FLAG = "mylocation";
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);

    AroundTaxiContract.Presenter mPresenter;

    //周边的出租车信息列表
    List<AroundTaxiInfo> mAroundTaxiInfoList = new ArrayList<>();

    //周边的出租车的marker的list
    List<Marker> mAroundTaxiMarkerList = new ArrayList<>();

    LatLng mLocateLatLng;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 不显示程序的标题栏
        setContentView(R.layout.activity_taxi_around_view);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);

        initAMap();
        assignView();
        initView();
        mPresenter = new AroundTaxiPresenter(this, SchedulerProvider.getInstance(), HttpService.Factory.create(Constants.BASE_URL_FOR_TAXI_ABOUT_INFO));
        //getAroundTaxiList();
    }

    private void initAMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
            setUpMap();
        }
        mSensorHelper = new SensorEventHelper(this);
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
    }

    private void requestPermission() {
        Dexter.withActivity(this)
                .withPermissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION
                ).withListener(new MultiplePermissionsListener() {
            @Override
            public void onPermissionsChecked(MultiplePermissionsReport report) {

                if (report.areAllPermissionsGranted()) {
                    //PushManager.getInstance().initialize(ActivityLogin.this, PushService.class);
                } else {
                    //PushManager.getInstance().initialize(ActivityLogin.this, PushService.class);
                    ToastUtil.showShort(ActivityTaxiAroundView.this, "我们需要本地存储，获取地理位置权限用来保证app的正常运行,请到系统设置里面进行相关设置");
                }
            }

            @Override
            public void onPermissionRationaleShouldBeShown(List<com.karumi.dexter.listener.PermissionRequest> permissions, PermissionToken token) {

            }

        }).check();
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }


    private void initData() {
        //初始化定位
        mlocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mlocationClient.setLocationListener(this);

        initLocationOption();

        //给定位客户端对象设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        //启动定位
        //mlocationClient.startLocation();
    }

    //初始化定位opion
    private void initLocationOption() {
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(false);
        //获取最近3s内精度最高的一次定位结果：
        //设置单次定位是否等待WIFI列表刷新 仅适用于单次定位，当设置为true时，连续定位会自动变为单次定位,定位精度会更高，但是定位速度会变慢1-3秒
        mLocationOption.setOnceLocationLatest(false);

        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(10000);

        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        //设置是否强制刷新WIFI，默认为true，强制刷新。
        mLocationOption.setWifiActiveScan(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        //注意：自 V3.1.0 版本之后setHttpTimeOut(long httpTimeOut)方法
        // 不仅会限制低功耗定位、高精度定位两种模式的定位超时时间，同样会作用在仅设备定位时。
        // 如果单次定位发生超时情况，定位随即终止；连续定位状态下当前这一次定位会返回超时，但按照既定周期的定位请求会继续发起。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
    }

    private void assignView() {
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTramcar = (TextView) findViewById(R.id.tv_tramcar);
        //fbTakeTaxi = (FloatingActionButton) findViewById(R.id.fb_take_taxi);
        tvTakeTaxi = (TextView) findViewById(R.id.tv_take_taxi);
    }

    private void initView() {
        RxView.clicks(ivBack)
                .throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        finish();
                    }
                });
        //前往有轨电车模块
        RxView.clicks(tvTramcar).throttleFirst(1000, TimeUnit.MILLISECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                Intent toTramcar = new Intent(ActivityTaxiAroundView.this, TramcarActivity.class);
                startActivity(toTramcar);
            }
        });
        RxView.clicks(tvTakeTaxi)
                .throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        /*//
                        Intent toCallTaxiKeFu = new Intent(ActivityTaxiAroundView.this, ActivityCallTaxiKeFu.class);
                        startActivity(toCallTaxiKeFu);*/
                        showCallTaxiKeFuDialog();
                    }
                });
    }

    private void showCallTaxiKeFuDialog() {
        final AlertDialog.Builder tipBd = new AlertDialog.Builder(this);
        String message = "是否拨打叫车服务热线：95128";
        SpannableString aimSpanStr = CommonUtil.getAimTextColorSpannableStr(message, getResources().getColor(R.color.black), getResources().getColor(R.color.title_bg_new), 0, 11);
        tipBd.setTitle("提示");
        tipBd.setMessage(aimSpanStr);
        tipBd.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                CommonUtil.toSysCallView("95128", ActivityTaxiAroundView.this);

            }
        });
        tipBd.setNegativeButton("取消", null);
        tipBd.show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
        //获取相关权限
        requestPermission();
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        } else {
            mSensorHelper = new SensorEventHelper(this);
            if (mSensorHelper != null) {
                mSensorHelper.registerSensorListener();

                if (mSensorHelper.getCurrentMarker() == null && mLocMarker != null) {
                    mSensorHelper.setCurrentMarker(mLocMarker);
                }
            }
        }

    }


    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        mMapView.onPause();
        deactivate();
        mFirstFix = false;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    @Override
    public void onLocationChanged(final AMapLocation aMapLocation) {
        if (mOnLocationChangeListener != null && aMapLocation != null) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {

                //mOnLocationChangeListener.onLocationChanged(aMapLocation);

                LatLng location = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                mLocateLatLng = location;
                Log.e("lonAndLat", aMapLocation.getLongitude() + " ," + aMapLocation.getLatitude());

                if (!mFirstFix) {
                    mFirstFix = true;
                    //addCircle(location, aMapLocation.getAccuracy());//添加定位精度圆
                    addMarker(location);//添加定位图标
                    mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
                } else {
                    /*mCircle.setCenter(location);
                    mCircle.setRadius(aMapLocation.getAccuracy());*/
                    mLocMarker.setPosition(location);
                }
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 15));

                getAroundTaxiList(String.valueOf(aMapLocation.getLongitude()), String.valueOf(aMapLocation.getLatitude()));


            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("定位失败信息", errText);
                ToastUtil.showShort(ActivityTaxiAroundView.this, "请开启定位功能");
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mOnLocationChangeListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            //mLocationOption = new AMapLocationClientOption();
            mLocationOption = new AMapLocationClientOption();
            initLocationOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
           /* Observable.interval(0,10*1000,TimeUnit.MILLISECONDS)
                    .compose(this.<Long>bindToLifecycle())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            Log.e("timeflys:",aLong/1000+("秒"));

                            //getAroundTaxiList(String.valueOf(aMapLocation.getLongitude()),String.valueOf(aMapLocation.getLatitude()));
                        }
                    });*/

        }
    }

    @Override
    public void deactivate() {
        mOnLocationChangeListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    /**
     * 添加Circle
     *
     * @param latlng 坐标
     * @param radius 半径
     */
    private void addCircle(LatLng latlng, double radius) {
        CircleOptions options = new CircleOptions();
        options.strokeWidth(1f);
        options.fillColor(FILL_COLOR);
        options.strokeColor(STROKE_COLOR);
        options.center(latlng);
        options.radius(radius);
        mCircle = aMap.addCircle(options);
    }

    /**
     * 添加Marker
     */
    private void addMarker(LatLng latlng) {
        if (mLocMarker != null) {
            return;
        }
        Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.navi_map_gps_locked);
        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mLocMarker = aMap.addMarker(options);
        //mLocMarker.setTitle(LOCATION_MARKER_FLAG);
    }

    @Override
    public void getAroundTaxiList(String curLon, String curLat) {
        mPresenter.getAroundTaxiList(curLon, curLat, "1000");
    }

    @Override
    public void onGetAroundTaxiListSuccess(List<AroundTaxiInfo> aroundTaxiInfos, int aroundTaxiCount) {
        mAroundTaxiInfoList.clear();
        mAroundTaxiInfoList.addAll(aroundTaxiInfos);
        mLocMarker.getOptions().title("提示:").snippet("周围有" + aroundTaxiCount + "辆出租车");

        aMap.clear();
        mLocMarker = aMap.addMarker(mLocMarker.getOptions());
        mLocMarker.showInfoWindow();
        showAroundTaxi(mAroundTaxiInfoList);

    }


    @Override
    public void onGetAroundTaxiListError(String tip) {

        aMap.clear();
        mLocMarker.getOptions().title("提示:").snippet("周围有0辆出租车");
        mLocMarker = aMap.addMarker(mLocMarker.getOptions());
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void dismissLoading() {

    }

    @Override
    public void setPresenter(AroundTaxiContract.Presenter presenter) {

    }


    private void showAroundTaxi(List<AroundTaxiInfo> aroundTaxiInfos) {
        mAroundTaxiMarkerList.clear();
        for (int i = 0; i < aroundTaxiInfos.size(); i++) {
            mAroundTaxiMarkerList.add(makeAnimationTaxiMarker(aroundTaxiInfos.get(i)));
        }

    }


    private Marker makeAnimationTaxiMarker(AroundTaxiInfo aroundTaxiInfo) {

        Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                R.drawable.ico_taxi_small);
        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(new LatLng((double) (aroundTaxiInfo.getLat() / 1E6), (double) (aroundTaxiInfo.getLon() / 1E6)));
        options.draggable(false);

        Marker marker = aMap.addMarker(options);


        Animation animation = new RotateAnimation(marker.getRotateAngle(), marker.getRotateAngle() + aroundTaxiInfo.getDirection());
        long duration = 1000L;
        animation.setDuration(duration);
        animation.setInterpolator(new LinearInterpolator());

        marker.setAnimation(animation);
        marker.startAnimation();

        return marker;
    }

}
